<template>
  <div id="approveconfirmcomp">
    <!-- Form-开始 -->
    <el-dialog :title="`验证${formTitle}医生`" width="500px" v-model="dialogFormVisible" draggable v-if="dialogFormVisible" @closed="closeDialog">
      <vxe-form ref="pagepanelnameForm" :data="form" :title-width="formLabelWidth" className="margin-bottom-sm">
        <vxe-form-item field="name" title="用户名称" span="24">
          <!-- <SelectDataList ref="employeeSelectRef" :url="'/api/user/getUserInfoList'" :displayField="[
              { title: '编号', props: 'code' }, //列标题
              { title: '名称', props: 'name' }
            ]" :inputKeyName="'seachValue'" :isPage="true" :placeholder="'点击选择员工'" @selectDataRow="SelectRowClick" v-model="form.name" /> -->
          <VxePulldownSelection ref="employeeSelectRef" :url="'/api/user/getUserInfoList'" @confirmClick="SelectRowClick" :tableColumn="[{ title: '编号', field: 'username' }, { title: '名称', field: 'realname' }]" :aimKeys="[{ formKey: 'code', rowKey: 'username' },{ formKey: 'id', rowKey: 'id' }, { formKey: 'name', rowKey: 'realname' }]" :displayTexts="['realname']" :displayTextObj="form.code" />
        </vxe-form-item>
        <vxe-form-item field="name" title="授权码" span="24">
          <vxe-input ref="pswInput" v-model="form.password" autocomplete="new-password" name="password" type="password" auto-complete="new-password" clearable @keydown="pswKeydown" />
        </vxe-form-item>
      </vxe-form>
      <div v-if="origin !== 2">
        <div class="line-bottom solid-top margin-bottom-sm"></div>
        <vxe-radio-group v-model="radioEditType" class="margin-top cu-list" style="width: 100%">
          <div class="cu-item readio-item">
            <vxe-radio :label="1" content="修改当前标本"></vxe-radio>
            <br />
          </div>
          <div class="cu-item readio-item">
            <vxe-radio :label="2" content="修改所有未审核标本"></vxe-radio>
            <br />
          </div>
          <div class="cu-item readio-item flex justify-between">
            <div class="" style="vertical-align: middle; width: 160px">
              <vxe-radio :label="3" content="指定标本号修改"></vxe-radio>
            </div>
            <vxe-input class="margin-left-sm" v-model="inputCodeRange" placeholder="eg:1-4,6,7-15" :disabled="radioEditType !== 3"></vxe-input>
          </div>
        </vxe-radio-group>
        <div class="line-bottom solid-top padding-top-sm padding-bottom-sm margin-top-sm margin-bottom-sm">
          <vxe-checkbox v-model="rememberDateTime" content="记忆授权时间"></vxe-checkbox>
        </div>

        <div>
          <vxe-radio-group v-model="radio" style="width: 100%" :disabled="!rememberDateTime" @change="radioChange">
            <el-row>
              <el-col :span="6">
                <vxe-radio-button :label="'24'" border content="24小时" style="width: 100%"></vxe-radio-button>
              </el-col>
              <el-col :span="6">
                <vxe-radio-button :label="'12'" border content="12小时" style="width: 100%"></vxe-radio-button>
              </el-col>
              <el-col :span="6">
                <vxe-radio-button :label="'5'" border content="5小时" style="width: 100%"></vxe-radio-button>
              </el-col>
              <el-col :span="6">
                <vxe-radio-button :label="'Today'" border content="当天" style="width: 100%"></vxe-radio-button>
              </el-col>
            </el-row>
            <div></div>
            <vxe-toolbar class-name="margin-top-sm">
              <template #buttons>
                <vxe-radio-button :label="'Self'" border content="自定义"></vxe-radio-button>
                <vxe-input :disabled="radio !== 'Self'" v-model="num" placeholder="可输入小数" type="float" :step="1" min="0.01" max="23.59" @change="numChange"></vxe-input>
                <el-tag type="danger" style="margin-left: 0.5em">小时</el-tag>
              </template>
            </vxe-toolbar>
          </vxe-radio-group>
          <el-row style="padding-top: 20px">
            <el-col :span="4">当前时间：</el-col>
            <el-col :span="20">{{ timeData.currentTime }}</el-col>
          </el-row>
          <el-row style="padding-top: 10px">
            <el-col :span="4">结束时间：</el-col>
            <el-col :span="20">{{ timeData.expressIn }}</el-col>
          </el-row>
        </div>
      </div>

      <div class="flex justify-end">
        <el-button type="primary" v-loading="showLoading" @click="cacheEmployeeInfo()">确定</el-button>
        <el-button @click="closeDialog()"> 取消</el-button>
      </div>
    </el-dialog>
    <!-- Form-结束 -->
  </div>
</template>
<script setup lang="ts">
import { ref, reactive, getCurrentInstance, watch, onMounted } from 'vue';
import { pageSizes, DateToString, formatDateTime, IsEmpty } from '@/utils/common';
import { VxeMessage, VxeNotifyType } from '@/utils/CommonMessage';
import { VXETable } from 'vxe-table';
import XEUtils from 'xe-utils';
import { AppStore } from '@/stores/store';//'../../../stores/store';
import axios from 'axios';
import SelectDataList from '@/components/SelectDataList.vue';
import VxePulldownSelection from '@/components/VxePulldownSelection.vue';
import { getOptionValueByCodeRptGroupOption } from '@/utils/SysOptionsHelper';

// 全局变量定义区 ==========
let { proxy }: any = getCurrentInstance();
let store = AppStore();
let showLoading = ref(false);

let dialogFormVisible = ref(false);

let props = defineProps({
  isLocall: String, //是否存储到本地
  IsShow: Boolean,
  origin: Number //来源，弹框在哪个地方打开的。1:快捷菜单,2:批次审核
  //modelValue: String, //输入框绑定参数
  // inputKeyName: String, //查询入参名称
  // placeholder: { type: String, default: '点击选择' } //弹框标题
}) as any;
const pswInput = ref(null);//密码框el对象
const employeeSelectRef = ref(null);//用户选择组件el对象
let curAction = ref('1');/**当前动作标记【1:初审、审核按钮触发；2:编辑左侧标本信息触发；3:全局组件快捷菜单触发】*/
defineExpose({
  initPage
})
onMounted(() => {
  //xgyssmrfs
  const a = getOptionValueByCodeRptGroupOption('xgyssmrfs');
  if (!IsEmpty(a)) {
    if (a === '0' || a === 0) {
      radioEditType.value = 1;
    }
    if (a === '1' || a === 1) {
      radioEditType.value = 2;
    }
    if (a === '3' || a === 3) {
      radioEditType.value = 3;
    }
  }
});
// 接收父组件传过来的弹框展开状态
function initPage(row: any, fmTitle, user: any, triggerSource: string) {
  form.id = '';
  form.code = '';
  form.name = '';
  curAction.value = '';
  form.password = '';
  /**系统参数默认取值 */
  //xgyssmrfs
  const a = getOptionValueByCodeRptGroupOption('xgyssmrfs');
  if (!IsEmpty(a)) {
    if (a === '0' || a === 0) {
      radioEditType.value = 1;
    }
    if (a === '1' || a === 1) {
      radioEditType.value = 2;
    }
    if (a === '3' || a === 3) {
      radioEditType.value = 3;
    }
  }
  dialogFormVisible.value = row;
  formTitle.value = fmTitle;
  /**判断事件来源 */
  if (!IsEmpty(triggerSource)) {
    curAction.value = triggerSource;
  }
  /**左侧编辑病人信息调用时 会传选择的人进来 */
  if (user && !IsEmpty(user.username)) {
    proxy.$nextTick(() => {
      form.code = user.username;
      form.id = user.id;
      form.name = user.realname;
      if (employeeSelectRef.value) {
        employeeSelectRef.value?.resetDisplayText(form.code, () => {
          pswInputFocus();
        });
      }
      pswInputFocus();
    });
  }
}

let origin = ref(props.origin);
//   //#region  变量
let KeyObj = { wtId: '', scheduleDate: '' };
let IsCallBackApprove = false;

let form = reactive({ seachValue: '', id: '', name: '', code: '', password: '' });
let loading = ref(false);
// let pageSizeList = PageSizeList;
// let pageSize = PageSizeList[0];
let formLabelWidth = '100px';
let radioEditType = ref(2);
let radio = ref('Today');
let rememberDateTime = ref(true);
let inputCodeRange = ref('');
let num = ref(1.0);
let timeData = reactive({
  currentTime: DateToString(new Date()),
  expressIn: formatDateTime(new Date().valueOf(), 'yyyy-MM-dd 23:59:59')
});

let formTitle = ref('');

//   //#region  Methods
/**密码框获取焦点 */
function pswInputFocus() {
  if (!pswInput.value) {
    setTimeout(() => {
      pswInputFocus();
    }, 500);
    return;
  }
  proxy.$nextTick(() => {
    form.password = '';
    pswInput.value?.focus();
  });
}
// 点击组件表格行
function SelectRowClick(e) {
  let a = {} as any;
  e.aimKeys.forEach(item => {
    a[item.formKey] = e.row[item.rowKey];
  });
  Object.assign(form, a);
  pswInput.value?.focus();
}

// 取消操作
function closeDialog() {
  IsCallBackApprove = false;
  formTitle.value = '审核';
  dialogFormVisible.value = false;
  form = { seachValue: '', id: '', name: '', code: '', password: '' };
  radioEditType.value = 2;
  radio.value = 'Today';
  proxy.$emit('closeSHowApproveConfirm');
}

async function cacheEmployeeInfo() {
  if (IsEmpty(form.name) || IsEmpty(form.code)) {
    VxeMessage('请选择医师！', VxeNotifyType.error);
    return;
  }
  if (IsEmpty(form.password)) {
    VxeMessage('请输入授权码!', VxeNotifyType.error);
    return;
  }
  const data = { params: { username: form.code, empowerNum: form.password } };
  loading.value = true;
  const res = await new Promise((resolve, reject) => {
    proxy.$http
      .get('/api/user/checkEmpowerNum', data)
      .then((res: any) => {
        if (res && res.status && res.status.code && res.status.code === 1 && res.data) {
          resolve(true);
        } else {
          resolve(false);
        }
      })
      .catch((err: any) => {
        resolve(false);
      });
  });

  /**第一步, 如果是批量审核授权验证，验证通过直接返回*/
  if (res && origin.value === 2) {
    proxy.$emit('Confirm', { reviewerId: form.id, name: form.name, code: form.code, type: 'chkmany' });
    loading.value = false;
    return;
  }

  /**第二步, */
  if (res) {
    let _action = '4';/**【1：初审】、【2：审核】、【3：检验】 、'4'：只修改审核人不做审核处理*/
    //#endregion 【验证通过，把数据保存在会话存储中】
    const pobj = { id: form.id, code: form.code, name: form.name, caid: '', expressin: new Date(formatDateTime(timeData.expressIn, 'yyyy-MM-dd hh:mm:ss')).valueOf() };
    if (formTitle.value === '初审' && rememberDateTime.value) {
      //store.setChkDoctorObj(pobj, true);
      _action = '1';
    } else {
      //store.setChkDoctorObj(pobj);
    }
    if (formTitle.value === '审核' && rememberDateTime.value) {
      //store.setChkDoctorObj(pobj, true);
      _action = '2';
    } else {
      //store.setChkDoctorObj(pobj);
    }
    if (formTitle.value === '检验' && rememberDateTime.value) {
      //store.setTestDoctorObj(pobj, true);
      _action = '3';
    } else {
      //store.setTestDoctorObj(pobj);
    }

    if (!IsEmpty(curAction.value) && curAction.value === '2' && formTitle.value === '审核') {
      _action = '4';
    }
    if (!IsEmpty(curAction.value) && curAction.value === '2' && formTitle.value === '检验') {
      _action = '3';
    }
    // #endregion

    if (_action === '1' || _action === '2' || _action === '4') {
      store.setChkDoctorObj(pobj, true);
    }
    else if (_action === '3') {
      store.setTestDoctorObj(pobj, true);
    }

    /**更新选项 */
    let resData = { edtType: radioEditType.value, codeRange: inputCodeRange.value, action: _action };
    proxy.$emit('AuthSuccess', resData);
    dialogFormVisible.value = false;
  }
  /**第三步, */
  /**第四步, */
  /**最后一步,如果授权失败,清楚记忆的缓存数据 */
  if (!res) {
    VxeMessage('授权验证失败', VxeNotifyType.error);
    const second = new Date(timeData.expressIn).getTime() - new Date().getTime(); //距清除审核人剩余的时间（毫秒）
    const time = setTimeout(() => {
      clearTimeout(time);
      sessionStorage.removeItem('locChkDoctor');
    }, second);
  }
  //loading.value = false;
}

//单选改变
function radioChange(e) {
  try {
    const numObj = 1;
    switch (e.label) {
      case '24':
        timeData.expressIn = DateToString(new Date().valueOf() + 24 * 60 * 60 * 1000);
        break;
      case '12':
        timeData.expressIn = DateToString(new Date().valueOf() + 12 * 60 * 60 * 1000);
        break;
      case '5':
        timeData.expressIn = DateToString(new Date().valueOf() + 5 * 60 * 60 * 1000);
        break;
      case 'Today':
        timeData.expressIn = formatDateTime(new Date().valueOf(), 'yyyy-MM-dd 23:59:59');
        break;
      case 'Self':
        timeData.expressIn = DateToString(new Date().valueOf() + num.value * 60 * 60 * 1000);
        break;
      default:
        break;
    }
  } catch (error) {
    //todo
  }
}
//自定义数值改变
function numChange(e) {
  if (radio.value && radio.value === 'Self') {
    timeData.expressIn = DateToString(new Date().valueOf() + num.value * 60 * 60 * 1000);
  }
}
/**密码框回车事件 */
function pswKeydown({ value, $event }) {
  if ($event && $event.keyCode === 13) {
    cacheEmployeeInfo();
  }
}
</script>
<style lang="scss" scope>
#pagepanelname {
  .tool {
    margin: 10px 15px;

    .el-row {
      .tool-left,
      .tool-right {
        background-color: bg-white;
      }

      .el-form-item {
        margin-top: 10px;
        margin-bottom: 10px;
      }
    }
  }

  .el-divider--vertical {
    height: 20px;
  }
}

.readio-item {
  height: 28px;
  line-height: 28px;
  vertical-align: middle;
}

.readio-item > label {
  margin-top: calc((28px - 16px) / 2);
}

.readio-item > div > label {
  margin-top: calc((28px - 16px) / 2);
}
</style>
